# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
import math

from odoo import api, fields, models, _
from odoo import SUPERUSER_ID
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_is_zero
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT


class PurchaseSupplementOrderWizard(models.TransientModel):
    _name = 'supplement.order.wizard'
    _description = 'Supplement Order Wizard'

    line_ids = fields.One2many(comodel_name='supplement.order.wizard.line', inverse_name='head_id')
    purchase_id = fields.Many2one('purchase.order', 'Purchase Order')

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        if self.env.context.get('active_id'):
            purchase = self.env['purchase.order'].browse(self.env.context.get('active_id'))
            line_ids = []
            for line in purchase.order_line:
                supplement_qty = line.product_qty - line.qty_received
                if supplement_qty <= 0:  # 为 0 不需要补货
                    continue
                line_ids.append((0, 0, {
                    'purchase_line_id': line.id,
                    'product_id': line.product_id.id,
                    'product_qty': line.product_qty,
                    'qty_received': line.qty_received,
                    'supplement_qty': supplement_qty,
                    'product_uom': line.product_uom,
                    'price_unit': line.price_unit
                }))

            res.update({
                'purchase_id': self.env.context.get('active_id'),
                'line_ids': line_ids

            })
            return res

    def confirm_repplement(self):
        for line in self.line_ids:
            if line.product_qty < line.qty_received:
                raise ValidationError(_("The supplementary quantity cannot exceed the remaining received quantity！"))
        self.purchase_id.with_context(supplement=self.id)._create_picking()

        for line in self.line_ids:
            line.purchase_line_id.update({'qty_received': line.purchase_line_id.qty_received + line.supplement_qty})


class PurchaseSupplementOrderLineWizard(models.TransientModel):
    _name = 'supplement.order.wizard.line'
    _description = 'Supplement Order Line Wizard'

    purchase_line_id = fields.Many2one('purchase.order.line', 'Purchase Order')
    product_id = fields.Many2one(comodel_name="product.product", string="Product")
    product_qty = fields.Float(string='Product Qty')
    qty_received = fields.Float(string='Received Qty')
    supplement_qty = fields.Float(string='Supplement Qty', required=True)
    product_uom = fields.Many2one('uom.uom', string='Uom')
    price_unit = fields.Float(string='Price Unit', digits='Product Price', )
    head_id = fields.Many2one(comodel_name='supplement.order.wizard')
